package com.sd365.permission.centre.service.util;

import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.constant.EntityConsts;
import com.sd365.permission.centre.dao.mapper.AuditMapper;
import com.sd365.permission.centre.dao.mapper.UserMapper;
import com.sd365.permission.centre.entity.Audit;
import com.sd365.permission.centre.entity.User;
import com.sd365.permission.centre.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@EnableScheduling
@Component
public class AutoAudit {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuditMapper auditMapper;

    @Autowired
    private SysLogService sysLogService;

    @Autowired
    IdGenerator idGenerator;

    private static String LOGIN_ACTION = "100";

    // 用户审计Map（key: user.code    value: 用户对应的Audit对象）
    private Map<String, Audit> userAuditMap;

    /**
     * （操作之前先把basic_audit中的数据清空）
     * 创建一个公用map，所有审计方法都对这个公用map进行添加修改操作
     * 所有审计方法结束后，将map中的auditList插入到数据库
     */
    //@Scheduled(cron = "0 0 0 * * ? * ")

    public void audit() {
        userAuditMap = new HashMap<>(); // 初始化用户审计Map
        longNoLoginAudit();
        //.... 补充审计方法
        //....

        // 将用户审计记录插入审计表中
        auditMapper.insertList(new ArrayList<>(userAuditMap.values()));
    }

    /**
     * 30天内未登录审计
     */
    public void longNoLoginAudit() {
        // 获取30内未登录用户列表
        List<User> users = userMapper.longNoLoginUserList();
        // 遍历用户列表，逐个用户进行长期未登录判断
        for (User user : users) {
            // 从map中拿出对应用户Audit对象，若没有的话，通过用户信息初始化Audit对象
            Audit audit = userAuditMap.getOrDefault(user.getCode(), createAudit(user));
            // 插入长期未登录信息
            audit.setLongNoLogin((byte) 1);
            audit.setResult(audit.getResult() + "长期未登录 ");
            // 将更新后的audit对象put进map中
            userAuditMap.put(user.getCode(), audit);
        }
    }



    /**
     * 通过用户信息初始化审计对象audit
     * @param user
     * @return
     */
    public Audit createAudit(User user) {
        Audit audit = new Audit();
        audit.setId(idGenerator.snowflakeId());
        audit.setCode(user.getCode());
        audit.setName(user.getName());
        audit.setDepartmentId(user.getDepartmentId());
        audit.setCreatedTime(new Date());
        audit.setUpdatedTime(new Date());
        audit.setStatus(EntityConsts.INITIAL_STATUS);
        audit.setVersion(EntityConsts.INITIAL_VERSION);
        return audit;
    }
}
